package com.jisf.driver.handler;

import com.alibaba.fastjson.JSON;
import com.jisf.driver.response.GlobalConstant;
import com.jisf.driver.response.Result;
import com.jisf.driver.utils.WebUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname AuthenticationEntryPointImpl
 * @Description TODO 用户认证异常
 * @Date 2022/4/18 15:57
 * @Created by jisf：【429627912@qq.com】
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Result result;
        if (e instanceof InternalAuthenticationServiceException){
            result = new Result(GlobalConstant.TOKEN_CODE, e.getMessage());
        }else if (e instanceof BadCredentialsException){
            result = new Result(GlobalConstant.TOKEN_CODE, "密码错误");
        }else {
            result = new Result(GlobalConstant.TOKEN_CODE, "用户认证失败请重新登录");
        }
        String json = JSON.toJSONString(result);
        WebUtil.renderString(response, json);
    }
}
